package com.insurance.controller;

import com.insurance.domain.ResponseResult;
import com.insurance.domain.entity.LoginUser;
import com.insurance.domain.entity.Permission;
import com.insurance.domain.entity.User;
import com.insurance.domain.entity.UserInfo;
import com.insurance.domain.enums.AppHttpCodeEnum;
import com.insurance.domain.vo.RouterVo;
import com.insurance.exception.SystemException;
import com.insurance.service.LoginService;
import com.insurance.utils.MenuTree;
import com.insurance.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    //用户登录
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        if(!StringUtils.hasText(user.getUsername())){
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    //获取用户信息
    @GetMapping("/getInfo")
    public ResponseResult getInfo(){

        //获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        User user = loginUser.getUser();
        //根据用户id查询权限信息
        //获取该用户拥有的角色权限信息
        List<Permission> permissionList = user.getPermissionList();
        //获取权限编码
        Object[] roles = permissionList.stream().filter(Objects::nonNull).map(Permission::getCode).toArray();
        //创建用户信息
        UserInfo userInfo=new UserInfo(user.getId(),user.getUsername(),user.getAvatar(),null,roles);
        //返回数据,把用户信息userInfo放出去
        return ResponseResult.okResult(userInfo);
    }

    @GetMapping("/getMenuList")
    public ResponseResult getMenuList(){
        //获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        User user = loginUser.getUser();
        //获取该用户拥有的角色权限信息
        List<Permission> permissionList = user.getPermissionList();
        //筛选当前用户拥有的菜单数据
        List<Permission> collect = permissionList.stream()
                //只筛选目录和菜单数据，按钮（2）不需要添加到路由菜单中
                .filter(item -> item != null && item.getType() != 2) //0-目录 1-菜单 2-按钮
                .collect(Collectors.toList());
        //生成路由数据
        List<RouterVo> routerVoList= MenuTree.makeRouter(collect,0L);
        //返回数据
        return ResponseResult.okResult(routerVoList);
    }

    @PostMapping("/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }
}
